package utils

import (
	"errors"
	"go_ruoyi/global"
	"log"
	"strings"
	"time"

	"github.com/golang-jwt/jwt/v5"
)

// 创建token
func CreateToken(userId int64, userName string, uuId string) (string, error) {
	user := map[string]any{
		"userId":   userId,
		"userName": userName,
		"tokenId":  uuId,
	}
	// 创建 JWT token
	token := jwt.NewWithClaims(jwt.SigningMethodHS384, jwt.MapClaims{
		"iss":  "goruoyi-auth-server",
		"user": user,
		"foo":  2,
		"exp":  time.Now().Add(time.Hour * 240).Unix(), // 设置过期时间为十天后
	})

	// 签名 JWT token
	signedToken, err := token.SignedString([]byte(global.Viper.GetString("jwt.privateKey")))
	if err != nil {
		log.Fatalf("Failed to sign token: %v", err)
	}
	signedToken = "GORUOYI " + signedToken
	return signedToken, nil
}

// 解析token
func ParseToken(tokenString string) (map[string]any, error) {
	if tokenString == "" {
		return nil, errors.New("token 为空，请重新登录")
	}
	if tokenString[0:8] != "GORUOYI " {
		return nil, errors.New("token 失效，请重新登陆")
	}
	tokenString = strings.TrimPrefix(tokenString, "GORUOYI ")
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, errors.New("token 解析失败，服务器内部错误")
		}
		return []byte(global.Viper.GetString("jwt.privateKey")), nil
	})
	if err != nil {
		return nil, err
	}
	//校验通过
	if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
		user, ok := claims["user"].(map[string]any)
		if !ok {
			return nil, errors.New("token 失效，请重新登陆")
		}

		return user, nil
	}
	return nil, errors.New("token 失效，请重新登陆")
}
